using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using C4F.DevKit.Contacts;
using C4F.DevKit.Contacts.Components;
using System.Windows.Media.Imaging;

namespace C4F.DevKit.Contacts.Controls
{
    [ToolboxItem(true), ToolboxBitmap(typeof(ContactDetails))]
    public partial class ContactDetails : UserControl
	{
        /// <summary>
        /// Represents the method used when a contacts is saved.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
		public delegate void ContactSavedEventHandler(object sender, ContactSavedEventArgs e);

        /// <summary>
        /// This event is raised when a contact is saved to the data store.
        /// </summary>
		public event ContactSavedEventHandler ContactSaved;

        /// <summary>
        /// Represents the method used when the user cancels the dialog.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
		public delegate void ContactSaveCanceledEventHandler(object sender, EventArgs e);

        /// <summary>
        /// This event is raised when a user cancels the dialog.
        /// </summary>
		public event ContactSaveCanceledEventHandler ContactSaveCanceled;

		#region Enum

        /// <summary>
        /// Used to determine what type of edit operation is being performed.
        /// </summary>
		public enum EditMode
		{
            /// <summary>
            /// Used when the current contact is being added
            /// </summary>
			Add = 1,

            /// <summary>
            /// Used when the current contact is being updated
            /// </summary>
			Update = 2,

            /// <summary>
            /// Used when the current contact is simple being displayed
            /// </summary>
			DisplayOnly = 3
		}

		#endregion Enum

		#region Private Data

		private EditMode _editMode = EditMode.DisplayOnly;
		private ContactsService _contactsService = null;
		private SimpleContactView _simpleContact = null;
        private string _picPath = string.Empty;
		
		#endregion Private Data

		#region Constructor

        /// <summary>
        /// Initiliazes the control
        /// </summary>
		public ContactDetails()
		{
			InitializeComponent();
		}

		#endregion Constructor

		#region Public Properties

        /// <summary>
        /// The EditMode for the current contact.
        /// </summary>
		[Browsable(false)]
		public EditMode Mode
		{
			get
			{
				return _editMode;
			}
			set
			{
				_editMode = value;
			}
		}

        /// <summary>
        /// The current contact being displayed or edited within this control.
        /// </summary>
		[Browsable(false)]
		public SimpleContactView SimpleContact
		{
			get
			{
				return _simpleContact;
			}
		}

        /// <summary>
        /// The ContactsService component to use when updating the contact.
        /// </summary>
		[Category("Contacts")]
		public ContactsService ContactsService
		{
			get
			{
				return _contactsService;
			}
			set
			{
				_contactsService = value;
			}

		}

		#endregion Public Properties

		#region Methods

		#region Event Handlers

		private void btnSave_Click(object sender, EventArgs e)
		{
            try
            {
                OnSave();
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
		}

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                OnSaveCanceled();
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            try
            {
                OnPictureClick();
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }

		#endregion EventHandlers	

		#region Public

        /// <summary>
        /// Refreshes the control with the current contact.
        /// </summary>        
		public void RefreshDetails()
		{
			if (_simpleContact != null)
			{
				PopulateFields();
			}
		}

        /// <summary>
        /// Sets the contact id to be used in the control. When setting this property, the control will requery the contacts for the specified contact and populate the fields with thie control.
        /// </summary>
        /// <param name="contactID">The ID of the contact to retrieve.</param>
        /// <remarks>If the contact id is empty, the current contact will be null.</remarks>
		public void SetContactID(string contactID)
		{
			if (contactID != string.Empty)
			{
				_simpleContact = _contactsService.GetSimpleContact(contactID);

				if (_simpleContact != null)
					PopulateFields();
			}
			else
			{
				_simpleContact = null;
			}
		}

		#endregion Public
		
		#region Private
        
        private void OnSave()
        {
            PrepareContact();
            _contactsService.SaveContact(_simpleContact);

            ContactSavedEventArgs args = new ContactSavedEventArgs();
            args.UpdateType = this.Mode == EditMode.Add ? ContactSavedEventArgs.EditMode.Added : ContactSavedEventArgs.EditMode.Updated;

            if (ContactSaved != null)
                ContactSaved(this, args);
        }

		private void OnSaveCanceled()
		{
			if (ContactSaveCanceled != null)
				ContactSaveCanceled(this, new EventArgs());
		}

		private void PrepareContact()
		{
            if (_editMode == EditMode.Add)
                _simpleContact = _contactsService.GetNewSimpleContact();
			
			_simpleContact.FirstName = txtFirst.Text;
			_simpleContact.LastName = txtLast.Text;
			_simpleContact.MiddleName = txtMiddle.Text;			    
			
			_simpleContact.Notes = txtNotes.Text;			
			_simpleContact.Title = txtTitle.Text;
            _simpleContact.Company = txtCompany.Text;
            _simpleContact.Department = txtDepartment.Text;
			_simpleContact.NickName = txtNickname.Text;
            //_simpleContact.Picas = pictureBox1.Image;

            if (!string.IsNullOrEmpty(_picPath))
                _simpleContact.NewPicFilePath = _picPath;

            _simpleContact.PersonalEmail1 = txtEmail.Text;
            _simpleContact.HomePhone = txtHomePhone.Text;
            _simpleContact.BusinessPhone = txtBusinessPhone.Text;
            _simpleContact.BusinessFax = txtFax.Text;
            _simpleContact.BusinessMobile = txtMobilePhone.Text;

            _simpleContact.HomeStreet = txtStreetHome.Text;
            _simpleContact.HomeCity = txtCityHome.Text;
            _simpleContact.HomeState = txtStateHome.Text;
            _simpleContact.HomeZip = txtZipHome.Text;
            _simpleContact.HomeCountry = txtCountryHome.Text;

            _simpleContact.BusinessStreet = txtStreetWork.Text;
            _simpleContact.BusinessCity = txtCityWork.Text;
            _simpleContact.BusinessState = txtStateWork.Text;
            _simpleContact.BusinessZip = txtZipWork.Text;
            _simpleContact.BusinessCountry = txtCountryWork.Text;
		}

        private void PopulateFields()
        {
            SimpleContactView simpleContact = _simpleContact;

            txtFirst.Text = simpleContact.FirstName;
            txtLast.Text = simpleContact.LastName;
            txtMiddle.Text = simpleContact.MiddleName;
            txtNotes.Text = simpleContact.Notes;
            txtTitle.Text = simpleContact.Title;
            txtCompany.Text = simpleContact.Company;
            txtDepartment.Text = simpleContact.Department;
            txtNickname.Text = simpleContact.NickName;
            txtEmail.Text = simpleContact.PersonalEmail1;
            pictureBox1.Image = simpleContact.PicAsImage;

            txtHomePhone.Text = simpleContact.HomePhone;
            txtMobilePhone.Text = simpleContact.PersonalMobile;
            txtFax.Text = simpleContact.BusinessFax;
            txtBusinessPhone.Text = simpleContact.BusinessPhone;

            txtStreetHome.Text = simpleContact.HomeStreet;
            txtCityHome.Text = simpleContact.HomeCity;
            txtStateHome.Text = simpleContact.HomeState.ToString();
            txtZipHome.Text = simpleContact.HomeZip;
            txtCountryHome.Text = simpleContact.HomeCountry;

            txtStreetWork.Text = simpleContact.BusinessStreet;
            txtCityWork.Text = simpleContact.BusinessCity;
            txtStateWork.Text = simpleContact.BusinessState.ToString();
            txtZipWork.Text = simpleContact.BusinessZip;
            txtCountryWork.Text = simpleContact.BusinessCountry;
        }

        private void DisplayException(Exception ex)
        {
            if (ex != null)
                MessageBox.Show(ex.ToString());
        }

        private void OnPictureClick()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            string filepath = string.Empty;

            dlg.CheckFileExists = true;
            dlg.Multiselect = false;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                _picPath = dlg.FileName;
                pictureBox1.Image = Image.FromFile(_picPath);                
            }
        }

		#endregion Private        

		#endregion Methods
	}
}
